from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from ..core.database import Base

class Module(Base):
    __tablename__ = "modules"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True, nullable=False, comment="模块名称")
    code = Column(String(50), unique=True, index=True, nullable=False, comment="模块代码")
    description = Column(Text, comment="模块描述")
    icon = Column(String(50), comment="模块图标")
    route = Column(String(200), comment="前端路由路径")
    parent_id = Column(Integer, ForeignKey("modules.id"), nullable=True, comment="父模块ID")
    order = Column(Integer, default=0, comment="排序号")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
    
    # 自引用关系，用于创建模块树
    parent = relationship("Module", remote_side=[id], back_populates="children")
    children = relationship("Module", back_populates="parent")

    def __repr__(self):
        return f"<Module(name='{self.name}', code='{self.code}')>"